<template>
    <div class="analysis-container">
        <!-- 对象数量趋势图 -->
        <!-- 使用柱状图显示随时间变化的对象数量
        异常时间段显示为红色柱状
        悬停显示详细信息 -->
        <div class="chart-container">
            <div ref="objectChart" class="chart"></div>
        </div>

        <!-- 行为分布图 -->
        <!-- 饼图展示各类行为占比
        支持百分比显示
        可旋转交互 -->
        <div class="chart-container">
            <div ref="behaviorChart" class="chart"></div>
        </div>

        <!-- 空间热力图 -->
        <!-- 显示对象在画面中的分布密度
        颜色越深表示出现频率越高
        基于置信度的热力值计算 -->
        <div class="chart-container">
            <div ref="heatmapChart" class="chart"></div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
    props: {
        framesData: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            objectChart: null,
            behaviorChart: null,
            heatmapChart: null
        }
    },
    watch: {
        framesData: {
            handler(newVal) {
                if (newVal.length > 0) {
                    this.initCharts()
                }
            },
            deep: true
        }
    },
    mounted() {
        this.initCharts()
    },
    beforeDestroy() {
        this.disposeCharts()
    },
    methods: {
        initCharts() {
            this.disposeCharts()

            // 对象数量趋势图
            this.objectChart = echarts.init(this.$refs.objectChart)
            this.objectChart.setOption(this.getObjectChartOption())

            // 行为分布图
            this.behaviorChart = echarts.init(this.$refs.behaviorChart)
            this.behaviorChart.setOption(this.getBehaviorChartOption())

            // 空间热力图
            this.heatmapChart = echarts.init(this.$refs.heatmapChart)
            this.heatmapChart.setOption(this.getHeatmapOption())
        },

        disposeCharts() {
            if (this.objectChart) {
                this.objectChart.dispose()
            }
            if (this.behaviorChart) {
                this.behaviorChart.dispose()
            }
            if (this.heatmapChart) {
                this.heatmapChart.dispose()
            }
        },

        // 处理数据：获取每帧对象数量
        getObjectCountData() {
            return this.framesData.map(frame => ({
                time: frame.time.toFixed(2),
                count: frame.objects.length,
                abnormal: frame.abnormal
            }))
        },

        // 处理数据：行为分布统计
        getBehaviorDistribution() {
            const behaviorMap = {}
            this.framesData.forEach(frame => {
                frame.objects.forEach(obj => {
                    behaviorMap[obj.behavior] = (behaviorMap[obj.behavior] || 0) + 1
                })
            })
            return Object.entries(behaviorMap).map(([name, value]) => ({
                name,
                value
            }))
        },

        // 处理数据：获取热力点数据
        getHeatmapData() {
            const points = [];
            const videoWidth = 1920; // 视频实际宽度
            const videoHeight = 1080; // 视频实际高度
            this.framesData.forEach(frame => {
                frame.objects.forEach(obj => {
                    try {
                        // 安全获取坐标参数
                        const [x, y, width, height] = obj.bbox.map(Number);
                        // 计算中心点坐标
                        const centerX = Math.min(videoWidth, Math.max(0, x + width / 2));
                        const centerY = Math.min(videoHeight, Math.max(0, y + height / 2));

                        // 确保数据有效性
                        if (
                            !isNaN(centerX) &&
                            !isNaN(centerY) &&
                            obj.confidence !== undefined
                        ) {
                            points.push([
                                centerX, // X坐标
                                centerY, // Y坐标
                                Math.min(1000, Math.max(0, obj.confidence)) // 热力值
                            ]);
                        }
                    } catch (e) {
                        console.warn('无效的bbox数据:', obj.bbox);
                    }
                });
            });
            return points;
        },

        // 对象数量图表配置
        getObjectChartOption() {
            const data = this.getObjectCountData()

            return {
                title: {
                    text: '对象数量趋势',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: params => {
                        try {
                            if (!params || params.length === 0) return '无可用数据'

                            const { data = {} } = params[0]
                            const time = data.time || '时间未知'
                            const count = data.count ?? 0
                            const status = data.abnormal ? '⚠️ 异常' : '正常'

                            return `
                            <strong>${time}</strong><br>
                            检测数量: <span style="color:${data.itemStyle.color}">${count}</span><br>
                            状态: ${status}
                        `
                        } catch (e) {
                            console.error('Tooltip Error:', e)
                            return '数据解析失败'
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    data: data.map(d => d.time),
                    name: '时间(ms)'
                },
                yAxis: {
                    type: 'value',
                    name: '对象数量'
                },
                series: [{
                    data: data.map(d => ({
                        value: d.count,
                        time: d.time,
                        count: d.count,
                        abnormal: d.abnormal,
                        itemStyle: {
                            color: d.abnormal ? '#ff4d4f' : '#1890ff'
                        }
                    })),
                    type: 'bar',
                    barWidth: '80%'
                }]
            }
        },

        // 行为分布图表配置
        getBehaviorChartOption() {
            const data = this.getBehaviorDistribution()

            return {
                title: {
                    text: '行为分布',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}: {c} ({d}%)'
                },
                series: [{
                    type: 'pie',
                    radius: ['40%', '70%'],
                    data: data,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            }
        },

        // 热力图配置
        getHeatmapOption() {
            // const data = this.getHeatmapData()
            // console.log(data)
            return {
                title: {
                    text: '对象空间分布热力图',
                    left: 'center'
                },
                tooltip: {
                    position: 'top',
                    formatter: params => {
                        return `坐标: (${params.value[0].toFixed(1)}, ${params.value[1].toFixed(1)})<br>置信度: ${params.value[2]}`;
                    }
                },
                grid: {
                    containLabel: true
                },
                xAxis: {
                    type: 'category',// 使用数值轴
                    min: 0,
                    max: 1920,
                    splitLine: { show: false },
                    name: 'X坐标(px)',
                    // axisLabel: {
                    //     formatter: value => `${value.toFixed(0)}px`
                    // }
                },
                yAxis: {
                    type: 'category',// 使用数值轴
                    min: 0,
                    max: 1080,
                    splitLine: { show: false },
                    name: 'Y坐标(px)',
                    // axisLabel: {
                    //     formatter: value => `${value.toFixed(0)}px`
                    // }
                },
                visualMap: {
                    min: 0,
                    max: 1000,
                    calculable: true,
                    orient: 'horizontal',
                    left: 'center',
                    bottom: 20,
                    inRange: {
                        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
                    }
                },
                series: [{
                    type: 'heatmap',
                    coordinateSystem: 'cartesian2d', // ✅ 关键配置
                    data: this.getHeatmapData().map(point => [
                        point[0], // x 坐标
                        point[1], // y 坐标
                        point[2]  // 热力值
                    ]),
                    // data: this.getHeatmapData(),
                    pointSize: 15,
                    blurSize: 30,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };
        }
    }
}
</script>

<style scoped>
.analysis-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 20px;
    padding: 20px;
}

.chart-container {
    background: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart {
    width: 100%;
    height: 400px;
}
</style>